package manage

import (
	"lingc/models"
	"lingc/services"
	"lingc/utils" // 导入 common 包
	"strings"

	"github.com/gin-gonic/gin"
)

// PageUser 获取所有用户
func PageAuthUser(c *gin.Context) {

	var dataRequest struct {
		Keywords string `json:"keywords" form:"keywords"`
		GroupId  string `json:"group_id" form:"group_id"`
		Status   string `json:"status" form:"status"`
		Page     int    `json:"page" form:"page"`
		PageSize int    `json:"pageSize" form:"pageSize"` // Exported field
	}
	// Bind query parameters to dataRequest
	if err := c.ShouldBind(&dataRequest); err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Invalid request parameters"})
		return
	}
	where := ""
	if dataRequest.Keywords != "" {
		keyword := "'%" + dataRequest.Keywords + "%'"
		where += " (`username` like " + keyword + " or `realname` like " + keyword + ")"
	}
	if dataRequest.GroupId != "" {
		if where != "" {
			where += " and "
		}
		where += " group_id = " + dataRequest.GroupId
	}
	if dataRequest.Status != "" {
		if where != "" {
			where += " and "
		}
		where += " status = " + dataRequest.Status
	}
	// log.Printf("PageUserWhere: %s", where)
	list, page, total, err := services.NewAuthUserService(utils.MysqlClient).PageAuthUserList(where, dataRequest.Page, dataRequest.PageSize)
	if err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err.Error()})
		return
	}
	utils.SendJSONResponse(c, utils.SuccessCode, gin.H{"list": list, "page": page, "total": total})
}

// GetUser 获取用户
func GetAuthUser(c *gin.Context) {

	var dataRequest struct {
		Keyword string `json:"keyword" form:"keyword"`
		Status  string `json:"status" form:"status"`
	}

	where := ""
	if err := c.ShouldBind(&dataRequest); err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Invalid request"})
		return
	}
	if dataRequest.Keyword != "" {
		keyword := "%" + dataRequest.Keyword + "%"
		where += " (username like " + keyword + " or realname like " + keyword + ")"
	}
	if dataRequest.Status != "" {
		if where != "" {
			where += " and "
		}
		where += " status = " + dataRequest.Status
	}

	user, err := services.NewAuthUserService(utils.MysqlClient).GetAuthUser(where)
	if err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err.Error()})
		return
	}
	utils.SendJSONResponse(c, utils.SuccessCode, gin.H{"data": user})
}

// CreateUser 创建用户
func CreateAuthUser(c *gin.Context) {

	var createRequest struct {
		Username string `json:"username" form:"username"`
		Password string `json:"password" form:"password"`
		Realname string `json:"realname" form:"realname"`
		Status   uint8  `json:"status" form:"status"`
		Avatar   string `json:"avatar" form:"avatar"`
		GroupID  uint   `json:"group_id" form:"group_id"`
	}
	if err := c.ShouldBindJSON(&createRequest); err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Invalid request parameters"})
		return
	}
	if createRequest.GroupID == 0 {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Invalid request parameters"})
		return
	}
	user := &models.AuthUserCreate{
		Username: createRequest.Username,
		Password: createRequest.Password,
		Realname: createRequest.Realname,
		Status:   createRequest.Status,
		Avatar:   createRequest.Avatar,
		GroupID:  createRequest.GroupID,
	}
	// log.Printf("CreateAuthUser: %v", user)
	data, err := services.NewAuthUserService(utils.MysqlClient).CreateAuthUser(user)
	if err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err.Error()})
		return
	}
	utils.SendJSONResponse(c, utils.SuccessCode, gin.H{"data": data})
}

// UpdateUser 更新用户
func UpdateAuthUser(c *gin.Context) {
	var createRequest struct {
		ID       uint   `json:"id" form:"id"`
		Username string `json:"username" form:"username"`
		Password string `json:"password" form:"password"`
		Realname string `json:"realname" form:"realname"`
		Status   uint8  `json:"status" form:"status"`
		Avatar   string `json:"avatar" form:"avatar"`
		GroupID  uint   `json:"group_id" form:"group_id"`
	}
	if err := c.ShouldBindJSON(&createRequest); err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "update Invalid request parameters"})
		return
	}
	user := &models.AuthUserUpdate{
		ID:       createRequest.ID,
		Username: createRequest.Username,
		Password: createRequest.Password,
		Realname: createRequest.Realname,
		Status:   createRequest.Status,
		Avatar:   createRequest.Avatar,
		GroupID:  createRequest.GroupID,
	}
	data, err := services.NewAuthUserService(utils.MysqlClient).UpdateAuthUser(user)
	if err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err.Error()})
		return
	}
	utils.SendJSONResponse(c, utils.SuccessCode, gin.H{"data": data})
}

// DeleteUser 删除用户
func DeleteAuthUser(c *gin.Context) {
	var createRequest struct {
		ID  uint   `json:"id" form:"id"`
		IDs string `json:"ids" form:"ids"`
	}
	if err := c.ShouldBind(&createRequest); err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Invalid request"})
		return
	}
	// log.Printf("DeleteAuthUser: %v", createRequest)

	if createRequest.ID == 0 && len(createRequest.IDs) == 0 {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Invalid request"})
		return
	}
	if createRequest.ID != 0 {
		if err := services.NewAuthUserService(utils.MysqlClient).DeleteAuthUser(createRequest.ID); err != nil {
			utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err.Error()})
			return
		}
	}

	if len(createRequest.IDs) == 0 {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "Invalid request"})
		return
	}
	idStrs := strings.Split(createRequest.IDs, ",")
	var ids []string
	for _, idStr := range idStrs {
		idStr = strings.TrimSpace(idStr)
		if idStr == "" {
			continue
		}
		ids = append(ids, idStr)
	}
	// Convert IDs slice to a format suitable for batch deletion
	if len(ids) == 0 {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": "No valid IDs provided"})
		return
	}
	if err := services.NewAuthUserService(utils.MysqlClient).DeleteAuthUsers(ids); err != nil {
		utils.SendJSONResponse(c, utils.ErrorCode, gin.H{"msg": err.Error()})
		return
	}
	// ... 这里添加删除用户的逻辑 ...
	utils.SendJSONResponse(c, utils.SuccessCode, gin.H{"msg": "Delete user"})
}
